# 5.10 Table Association Operations

JFinal ActiveRecord natively supports table association operations, so there is no need to learn anything new—a classic case of "less is more." There are mainly two ways to perform table association operations: First, directly use SQL to get associated data; Second, add methods in the Model to fetch associated data.

Suppose there are two database tables: user and blog, and there is a one-to-many relationship from user to blog. The blog table uses user_id to associate with the user table. The following code demonstrates how to use the first method to get user_name:

public void relation() {
  String sql = "select b.*, u.user_name from blog b inner join user u on b.user_id=u.id where b.id=?";
  Blog blog = Blog.dao.findFirst(sql, 123);
  String name = blog.getStr("user_name");
}
1
2
3
4
5

The code below demonstrates the second method for retrieving the associated User in Blog and the associated Blog in User:

public class Blog extends Model<Blog>{
    public static final Blog dao = new Blog().dao();
    
    public User getUser() {
       return User.dao.findById(get("user_id"));
    }
}
 
public class User extends Model<User>{
    public static final User dao = new User().dao();
    
    public List<Blog> getBlogs() {
       return Blog.dao.find("select * from blog where user_id=?", get("id"));
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

The above code creates a new dao object within the specific Model; this usage is solely for table association operations. For other cases, the dao object should be held by the Service layer.

Last Updated: 9/21/2023, 8:42:09 AM